#include "stdafx.h"
#include "ImmStuff.h"
#include "UiClass.h"
#include "StatusClass.h"
#include "CompAndCandWnd.h"

//global variables definition
HINSTANCE ImmStuff::hInst = NULL;
HKL ImmStuff::hPygHkL = NULL;
UINT ImmStuff::uNumTransKey = 0;

BOOL ImmStuff::ImmRegisterClass(HINSTANCE hInstance)
{
	BOOL ret = TRUE;
	ret &= UiClass::Register(hInstance);
	ret &= StatusClass::Register(hInstance);
	ret &= CompAndCandWnd::Register(hInstance);
	return ret;
}

VOID ImmStuff::ImmUnRegisterClass(HINSTANCE hInstance)
{
	UiClass::UnRegister(hInstance);
	StatusClass::UnRegister(hInstance);
	CompAndCandWnd::UnRegister(hInstance);
}

HKL ImmStuff::GetPygHKL()
{
    DWORD dwSize;
    DWORD dwi;
    HKL hKL = 0;
    HKL *lphkl;

    dwSize = GetKeyboardLayoutList(0, NULL);

    lphkl = (HKL *)GlobalAlloc(GPTR, dwSize * sizeof(DWORD));

    if (!lphkl)
        return NULL;

    GetKeyboardLayoutList(dwSize, lphkl);


    for (dwi = 0; dwi < dwSize; dwi++)
    {
        TCHAR szFile[32];
        HKL hKLTemp = *(lphkl + dwi);
        ImmGetIMEFileName(hKLTemp, szFile, sizeof(szFile));

        if (!_tcsicmp(szFile, IMENAME))
        {
             hKL = hKLTemp;
             goto exit;
        }
    }
exit:

    GlobalFree((HANDLE)lphkl);
    return hKL;
}

VOID ImmStuff::UpdateIndicIcon(HIMC hIMC)
{
    HWND hwndIndicate;
    BOOL fOpen = FALSE;
    LPINPUTCONTEXT lpIMC;

    if (!hPygHkL)
    {
       hPygHkL = GetPygHKL();
       if (!hPygHkL)
           return;
    }

    hwndIndicate = FindWindow(INDICATOR_CLASS, NULL);

    if (hIMC)
    {
        lpIMC = ImmLockIMC(hIMC);
        if (lpIMC)
        {
            fOpen = lpIMC->fOpen;
            ImmUnlockIMC(hIMC);
        }
    }

    if (IsWindow(hwndIndicate))
    {
        ATOM atomTip;

        atomTip = GlobalAddAtom(ATOMTIP);
        PostMessage(hwndIndicate, INDICM_SETIMEICON, 
                    fOpen ? 1 : (-1), (LPARAM)hPygHkL);
        PostMessage(hwndIndicate, INDICM_SETIMETOOLTIPS, 
                    fOpen ? atomTip : (-1), (LPARAM)hPygHkL);
        PostMessage(hwndIndicate, INDICM_REMOVEDEFAULTMENUITEMS, 
                    // fOpen ? (RDMI_LEFT | RDMI_RIGHT) : 0, (LPARAM)hMyKL);
                    fOpen ? (RDMI_LEFT) : 0, (LPARAM)hPygHkL);
    }
}
